﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Microsoft Corporation" file="Program.cs">
//   Copyright © Microsoft Corporation.  All Rights Reserved.  
// This code released under the terms of the 
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
// </copyright>
// <summary>
//   The resx translator program.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Microsoft.MCSUK.RESXTranslator
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.IO;
    using System.Resources;
    using System.Windows.Forms;

    using Microsoft.MCSUK.RESXTranslator.Properties;

    /// <summary>
    /// The Translator program
    /// </summary>
    public static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        public static void Main()
        {
            // look for arguments
            TranslatorParameters parameters;
            bool abortStartUp;
            if (ValidateArguments(Environment.GetCommandLineArgs(), out parameters, out abortStartUp))
            {
                try
                {
                    // process RESX
                    var translationResult = TranslatorTools.TranslateResXFile(
                        parameters.SourceResxFile,
                        parameters.FromCulture,
                        parameters.ToCulture,
                        parameters.ToCulture,
                        parameters.ClientID,
                        Console.Write, 
                        null);
                    Console.WriteLine(Resources.LogTranslationCompleted);
                    Console.WriteLine(string.Format(CultureInfo.CurrentCulture, Resources.TranslationsProcessed, translationResult.FileCount, translationResult.StringCount, translationResult.CharacterCount));
                }
                catch (Exception ex)
                {
                    TranslatorTools.LogStatus(
                        ("An error occured. The error is: " + ex.Message), MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                if (abortStartUp)
                {
                    return;
                }

                // no arguments so run as a forms application
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                var translator = new ResxTranslatorForm(); 
                if (!string.IsNullOrEmpty(parameters.ClientID))
                {
                    translator.AzureClientID = parameters.ClientID;
                }

                if (!string.IsNullOrEmpty(parameters.ClientSecret))
                {
                    translator.AzureClientSecret = parameters.ClientSecret;
                }

                Application.Run(translator);
            }
        }

        /// <summary>Command line argument validation</summary>
        /// <param name="args">Command line arguments</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="abortStartup">The abort Startup.</param>
        /// <returns>Value indicating whether cms line args are correct</returns>
        private static bool ValidateArguments(ICollection<string> args, out TranslatorParameters parameters, out bool abortStartup)
        {
            abortStartup = false;
            parameters = new TranslatorParameters();

            // Check if user is asking for help with the syntax or has not passed 
            if (args.Count <= 1)
            {
                return false;
            }
            else
            {
                // store args in variables
                foreach (var argument in args)
                {
                    string argumentName;
                    var argumentValue = string.Empty;
                    var valueSeperatorIndex = argument.IndexOf(':');
                    if (valueSeperatorIndex > 0)
                    {
                        argumentValue = argument.Substring(valueSeperatorIndex + 1);
                        argumentName = argument.Substring(1, (valueSeperatorIndex - 1));
                    }
                    else
                    {
                        argumentName = argument;
                    }

                    if (!String.IsNullOrEmpty(argumentName))
                    {
                        switch (argumentName.ToLower())
                        {
                            case "?":
                                ShowHelp();
                                abortStartup = true;
                                break;
                            case "pathtosourceresx":
                            case "source":
                                parameters.SourceResxFile = argumentValue;
                                break;
                            case "fromculture":
                                try
                                {
                                    parameters.FromCulture = new CultureInfo(argumentValue);
                                }
                                catch (ArgumentException)
                                {       
                                }

                                break;
                            case "toculture":
                                try
                                {
                                    parameters.ToCulture = new CultureInfo(argumentValue);
                                }
                                catch (ArgumentException)
                                {
                                }

                                break;
                            case "clientid":
                                parameters.ClientID = argumentValue;
                                break;
                            case "clientsecret":
                                parameters.ClientSecret = argumentValue;
                                break;
                            default:
                                break;
                        }
                    }
                }

                // set the fact that we have process arguments                
                return parameters.IsValid();
            }
        }

        /// <summary>
        /// Shows a help screen for the comand line parameters
        /// </summary>
        private static void ShowHelp()
        {
            var help = new CommandLineHelp { HelpContent = { Rtf = Properties.Resources.CommandLineHelp } };
            help.ShowDialog();
        }

        /// <summary>
        /// Parameters for the translator
        /// </summary>
        private struct TranslatorParameters
        {
            /// <summary>
            /// Source ResxFile
            /// </summary>
            public string SourceResxFile;

            /// <summary>
            /// The culture to translate from
            /// </summary>
            public CultureInfo FromCulture;

            /// <summary>
            /// The culture to translate to
            /// </summary>
            public CultureInfo ToCulture;

            /// <summary>
            /// The Azure Data Market ClientID
            /// </summary>
            public string ClientID;

            /// <summary>
            /// The Azure Data Market ClientSecret
            /// </summary>
            public string ClientSecret;

            /// <summary>
            /// Checks if parameters are valid / complete
            /// </summary>
            /// <returns>Value indicating whether parameters are valid</returns>
            internal bool IsValid()
            {
                return File.Exists(this.SourceResxFile) && (this.FromCulture != null) && (this.ToCulture != null)
                       && !string.IsNullOrEmpty(this.ClientID) && !string.IsNullOrEmpty(this.ClientSecret);
            }
        }
    }
}
